package com.lance.answer.gui.answer.gk.answer.task;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.lance.answer.dto.CompleteInfo;
import com.lance.answer.gui.answer.AnswerObject;
import com.lance.answer.gui.answer.DealJsonString;
import com.lance.answer.gui.answer.Util;
import com.lance.answer.gui.answer.gk.answer.AnswerDTO;
import com.lance.answer.util.HttpClientUtil;
import com.lance.answer.util.MD5Utils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.json.Json;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.time.Duration;
import java.util.*;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.TimeUnit;

@Slf4j
public class DoEngAnswerTask extends Thread {


    private final String driverPath;
    private final LinkedBlockingDeque<AnswerDTO> answerDTOS;

    public DoEngAnswerTask(String driverPath, LinkedBlockingDeque<AnswerDTO> answerDTOS) {
        this.driverPath = driverPath;
        this.answerDTOS = answerDTOS;
    }

    @SneakyThrows
    @Override
    public void run() {

        while (answerDTOS.size() > 0) {
            AnswerDTO answerDTO = answerDTOS.take();
            String userName = answerDTO.getUsername();
            String password = answerDTO.getPwd();
            log.info("任务：{} 剩余 {} 行 用户名：{} 密码：{}",
                    Thread.currentThread().getName(), answerDTOS.size(), userName, password);
            run(driverPath, answerDTO);
            //todo
        }

        if (answerDTOS.size() == 0) {
            log.info("课程所有用户均已执行完毕，系统将在20min后结束");
            TimeUnit.MINUTES.sleep(20);
            return;
        }
    }


    // 管理学基础 2065001457555 19940419
    public static void run(String driverPath, AnswerDTO answerDTO) throws Exception {


        List<String> urlTasks = Lists.newArrayList();
        urlTasks.addAll(answerDTO.getAnswerUrl());
        Map<String, AnswerObject> answers = answerDTO.getAnswers();
        Map<String, AnswerObject> originAnswers = answerDTO.getOriginAnswers();
        String subjectName = answerDTO.getSubjectName();
        String userName = answerDTO.getUsername();
        String teacherName = answerDTO.getTeacher();
        String password = answerDTO.getPwd();
        boolean commit = answerDTO.isCommit();
        boolean push = answerDTO.isPush();



        //=============================12-19add======================
        String filePath = "libs//answerInfo//" +teacherName+"//"+ subjectName;
        //  String filePath = "D:\\project\\answer-tool\\libs\\answerInfo\\" + subjectName;

        if (!new File(filePath).exists()) {
            new File(filePath).mkdirs();
        }

        filePath = filePath + "//" + userName + ".txt";

        File completeInfoFile = new File(filePath);
        if (!completeInfoFile.exists()) {
            completeInfoFile.createNewFile();
        }
        InputStream inputStream = new FileInputStream(completeInfoFile);
        String completeInfoStr = IOUtils.toString(inputStream, "UTF-8");
        List<CompleteInfo> completeInfoList = JSONObject.parseArray(completeInfoStr, CompleteInfo.class);
        if (null == completeInfoList) {
            completeInfoList = Lists.newArrayList();
        }
        Set<String> haveCompleteHomeWorkUrlSet = Sets.newHashSet();
        for (CompleteInfo info : completeInfoList) {
            if (info.isComplete()) {
                haveCompleteHomeWorkUrlSet.add(info.getHomeworkUrl());
            }
        }

        // 定义是否开启浏览器没有这门课程
        boolean isStartChrome = false;

        for (String urlTask : urlTasks) {
            if (!haveCompleteHomeWorkUrlSet.contains(urlTask)) {
                isStartChrome = true;
                break;
            }
        }
        for (CompleteInfo info : completeInfoList) {
            if ("没有这门课程！".equals(info.getSummary())) {
                isStartChrome = false;
                break;
            }
        }

        if (!isStartChrome) {
            return;
        }

        //=============================12-19add======================


//        try {
//            // 随机休眠，防止浏览器同时加载，CPU受不了。
//            Thread.sleep(new Random().nextInt(40)*1000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }


        WebDriver driver = Util.getDriver(driverPath);
        //String url = "http://student.ouchn.cn/";
        String url = "http://passport.ouchn.cn/Account/Login?ReturnUrl=%2Fconnect%2Fauthorize%2Fcallback%3Fclient_id%3Dstudentspace%26redirect_uri%3Dhttp%253A%252F%252Fstudent.ouchn.cn%252F%2523%252Fsignin-oidc%2523%26response_type%3Did_token%2520token%26scope%3Dopenid%2520profile%2520ouchnuser%2520ouchnstudentspaceapi%2520offline_access%26state%3Dca1cb5d0270b49fdaea508b8a846c457%26nonce%3Dd257df51b0a141ac8ed35b1caf59ef4c";
        driver.get(url);
        Thread.sleep(3000);
        //Util.login(driver, "2065001457555", "19940419");
        Util.login(driver, userName, password);
        Util.switchToFirst(driver);
        Thread.sleep(3000);
        // 形考作业的链接 管理学
        //List<String> urlTasks = Util.getCourseTaskUrl(driver, CourseTypeEnum.BasicManagement.name);
        //List<String> urlTasks = Util.getCourseTaskUrl(subjectCode);

        try {
            String title = driver.findElement(By.cssSelector("h2[class='title']")).getText();
            if(title.contains("试点")){
                driver.close();
                driver.quit();
                return;
            }
        }catch (Exception e){

        }


        //chromeDriver.navigate().refresh();
        for (WebElement we : driver.findElements(By.className("media-body"))) {
            Util.switchToFirst(driver);
            // 找到管理学基础
            String mediaTitle = we.findElement(By.className("media-title")).getText();

            if (!mediaTitle.contains(subjectName)) {
                continue;
            }
            //点击进入学习的按钮
            WebElement studyButton = we.findElement(By.cssSelector("button[class='btn bg-primary']"));
            studyButton.click();
            //Util.switchToLast(driver);
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        System.out.println(urlTasks.toString());

        Util.switchToLast(driver);
        String viewUrl = driver.getCurrentUrl();
        viewUrl = viewUrl+"&test=1";
        driver.get(viewUrl);

        Thread.sleep(5000);


        urlTasks.clear();


        for (WebElement we : new WebDriverWait(driver, Duration.ofSeconds(20)).until((ExpectedCondition<List<WebElement>>)
                d -> d.findElements(By.tagName("a")))) {
            String href = we.getAttribute("href");
            if(Strings.isNullOrEmpty(href)||!href.contains("quiz")){
                continue;
            }
            if("进入形考".equals(we.getText())){
                urlTasks.add(href);
            }
            if(we.getText().contains("次形考")){
                urlTasks.add(href);
            } if(we.getText().contains("形成性考核")){
                urlTasks.add(href);
            }
        }

        for (String urlTask : urlTasks) {

            //=============================12-19add======================
            if (haveCompleteHomeWorkUrlSet.contains(urlTask)) {
                continue;
            }
            //=============================12-19add======================


            // FIXME 当完成第一份形考任务时，必须提交，否则会弹出 ”是否保存当前页面“消息
            driver.get(urlTask);
            Thread.sleep(5 * 1000);
//=============================12-19add======================

            // 点击继续作业
            boolean isGoOn = true;
            CompleteInfo completeInfo = new CompleteInfo();
            try {
                String scoreString = driver.findElement(By.id("feedback")).getText();
                String[] strs = scoreString.split("/");
                String s1 =strs[0].trim() ;
                s1 =s1.replaceAll("[^.^0-9]", "");
                String s2 = strs[1].trim();
                s2 =s2.replaceAll("[^.^0-9]", "");

                float s = Float.parseFloat(s1) / Float.parseFloat(s2);
              //  if (s > 0.95) {
                if (s > 0.85) {
                    completeInfo.setScore(s1);
                    System.err.println("成绩已达到，跳过");
                    isGoOn = false;
                }
            }catch (Exception e){

            }

            if(!isGoOn){
                boolean hasGoOn = false;
                for (WebElement we : driver.findElements(By.cssSelector("button[class='btn btn-secondary']"))) {
                    if (!Strings.isNullOrEmpty(we.getText()) && "继续上次试答".equals(we.getText().trim())) {
                        hasGoOn = true;
                    }
                }
                if (!hasGoOn) {
                    completeInfo.setComplete(true);
                    completeInfo.setHomeworkUrl(urlTask);
                    completeInfoList.add(completeInfo);
                    continue;
                }
            }

            //=============================12-19add======================

            try {
                WebElement doWorkArea = driver.findElement(By.cssSelector("div[class='box py-3 quizattempt']"));
                doWorkArea.findElement(By.cssSelector("button[class='btn btn-secondary']")).click();
            } catch (Exception e) {
                System.err.println("taskUrl:" + urlTask + "  occur error");
                e.printStackTrace();
            }
            Thread.sleep(2 * 1000);
            //回到试题首页
            WebElement element = driver.findElement(By.id("quiznavbutton1"));
            element.click();
            Thread.sleep(2 * 1000);
            // 回到首页
            //Util.goHomePageIndex(driver);
            boolean hashNextPage = true;
            while (hashNextPage) {
                try {
                    Thread.sleep(4000);
                    // 单个页面的所有题目的集合
                    List<WebElement> singlePageQuestion = Util.getSinglePageQuestionList(driver);
                    // 遍历每个问题|题目


                    for (WebElement singleSubject : singlePageQuestion) {

                        WebElement contentElement = singleSubject.findElement(By.className("content"));

                        String title ;
                        title = Util.getTitle(contentElement);
                        //兼容特殊字符
                        title = Util.dealContent(title);

                        String questionCode = MD5Utils.encode(subjectName + title);

                        Map<String,String> map = Maps.newHashMap();

                        map.put("A.","0");
                        map.put("A","0");
                        map.put("a.","0");
                        map.put("a","0");
                        map.put("B.","1");
                        map.put("B","1");
                        map.put("b.","1");
                        map.put("b","1");
                        map.put("C.","2");
                        map.put("C","2");
                        map.put("c.","2");
                        map.put("c","2");
                        map.put("D.","3");
                        map.put("D","3");
                        map.put("d.","3");
                        map.put("d","3");
                        map.put("E.","4");
                        map.put("E","4");
                        map.put("T","0");
                        map.put("F","1");



                        AnswerObject answerObject = answers.get(questionCode);

                        if (answerObject == null) {
                            answerObject = originAnswers.get(DealJsonString.removeSpace(title));
                        }
                        if (answerObject == null) {
                            answerObject = originAnswers.get(DealJsonString.saveZhWord(title));
                        }
                        if(answerObject==null){
                            System.err.println("title:"+title);
                            continue;
                        }



                        WebElement answerElement = Util.findByClassName(contentElement, "answer");

                        System.err.println("answerObject:"+ JSON.toJSONString(answerObject));

                        // 填空
                        if(answerObject.getQuestionType().equals("6")){

                            LinkedList<String> realAnswers =  answerObject.getAnswers();
                            System.err.println("realAnswers:"+ JSON.toJSONString(realAnswers)+"code:"+answerObject.getQuestionCode());

                            try {
                                List<WebElement>inputList =  singleSubject.findElements(By.cssSelector("input[class^='select custom-select']"));
                                if(inputList.size()<1){
                                    //form-control mb-1
                                    inputList.addAll(singleSubject.findElements(By.cssSelector("input[class^='form-control mb-1']")));
                                }
                                System.err.println("inputList.size():"+inputList.size());
                                System.err.println();
                                for(int i = 0 ;i<inputList.size();i++){
                                    inputList.get(i).sendKeys( realAnswers.get(i));
                                }
                            }catch (Exception e){
                                // e.printStackTrace();
                            }

                            try {
                                List<WebElement> selectList =  singleSubject.findElements(By.cssSelector("select[class^='select custom-select']"));
                                System.err.println("selectList.size():"+selectList.size());
                                for(int i = 0 ;i<selectList.size();i++){
                                    System.err.println("i="+i+"   value:"+realAnswers.get(i)+answerObject.getQuestionCode());
                                    Select select = new Select(selectList.get(i));
                                    String answer = realAnswers.get(i);
                                    String value = map.get(answer);
                                    if(null!=value){
                                        select.selectByValue(map.get(realAnswers.get(i)));
                                    }else {
                                        List<WebElement>  options = selectList.get(i).findElements(By.tagName("option"));
                                        System.err.println("??:options.size()"+options.size());
                                        int k = 0;
                                        for(WebElement option:options){
                                            if(!Strings.isNullOrEmpty(option.getText())&&
                                                    Util.dealContent(option.getText()).equals(Util.dealContent(answer))){
                                                select.selectByValue(String.valueOf(--k));
                                            }else {
                                                k++;
                                            }
                                        }
                                    }
                                }


                            }catch (Exception e){
                                // e.printStackTrace();
                            }


                            continue;
                        }

                        if (null != answerElement) {
                            // 开始答题
                            Util.doExercise(driver, answerElement, answerObject.getQuestionType(), answerObject.getAnswers());
                        }else {
                            // 如果为空就是填空题 是没有答案对比的
                            Util.doExercise(driver, singleSubject, answerObject.getQuestionType(), answerObject.getAnswers());
                        }
                        //  FIXME 此时答案是没有保存的，要点击结束试答题
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    Thread.sleep(2000);
                    // FIX ME 获取当前页面的下一页信息 设置为while还是有下一页就继续循环
                    WebElement nextPage = Util.findNextPage(driver);
                    if (nextPage != null) {
                        nextPage.click();
                    } else {
                        hashNextPage = false;
                        // FIXME  此时答案是没有保存的，要点击结束试答题 当没有下一页的时候，可以选择提交
                    }
                }
            }


            Thread.sleep(2000);

            //回到试题首页 (保存最后一题答案)
           /* WebElement element2 = driver.findElement(By.id("quiznavbutton1"));
            element2.click();*/

            WebElement submitbtns = driver.findElement(By.className("submitbtns"));
            WebElement next = submitbtns.findElement(By.cssSelector("input[name='next']"));
            next.click();
            Thread.sleep(2000);

            if (!commit) {
                log.info("答案不提交");
                TimeUnit.SECONDS.sleep(2);
                continue;
            }

            //提交答案
            List<WebElement> saveButtons = driver.findElements(By.cssSelector("button[type='submit']"));
            //System.out.println("提交");
            //System.out.println(saveButtons.size());
            if (!CollectionUtils.isEmpty(saveButtons)) {
                for (WebElement webElement : saveButtons) {
                    String text = webElement.getText();
                    if (text.contains("提交")) {
                        webElement.click();
                    }
                }
            }

            TimeUnit.SECONDS.sleep(3);
            //全部提交
            //提交答案

            List<WebElement> confirmation = driver.findElements(By.className("confirmation-dialogue"));
            //System.out.println("确认弹框");
            //System.out.println(confirmation.size());
            //System.out.println(confirmation.toString());
            if (!CollectionUtils.isEmpty(confirmation)) {
                for (WebElement webElement : confirmation) {
                    List<WebElement> submitElement = webElement.findElements(By.tagName("input"));
//                    System.out.println("再次确认按钮");
//                    System.out.println(submitElement.size());
                    if (!CollectionUtils.isEmpty(submitElement)) {
                        for (WebElement element1 : submitElement) {
                            String value = element1.getAttribute("value");
//                            System.out.println("不是空的");
//                            System.out.println(value);
//                            System.out.println("按钮长这样");
//                            System.out.println(element1.toString());
                            if (value.contains("提交")) {
                                //点击确认后页面会刷新,此时为了防止丢到元素抛异常，这里直接获取第一个，不再循环
                                element1.click();
                                break;
                            }

                        }
                    }
                }
            }


            List<WebElement> submitButtons = driver.findElements(By.tagName("input"));
            //System.out.println("空的吗");
            //System.out.println(submitButtons.toString());
            if (!CollectionUtils.isEmpty(submitButtons)) {
                for (WebElement webElement : submitButtons) {
                    String text = webElement.getText();
                    //System.out.println("不是空的");
                    //System.out.println(text);
                    if (text.contains("提交")) {
                        webElement.click();
                    }
                }
            }

            TimeUnit.SECONDS.sleep(2);

            //=============================12-19add======================
            try {
                //判断是否符合要求
                Map<String, String> scoreMap = new HashMap<>();
                WebElement tbody = driver.findElement(By.tagName("tbody"));
                List<WebElement> trs = tbody.findElements(By.tagName("tr"));
                for (WebElement tr : trs) {
                    //th
                    WebElement th = tr.findElement(By.tagName("th"));
                    //td
                    WebElement td = tr.findElement(By.tagName("td"));
                    scoreMap.put(th.getText().trim(), td.getText().trim());
                }
                String score = scoreMap.get("分数");
                String[] strs = score.split("/");
                float s = Float.valueOf(strs[0]) / Float.valueOf(strs[1]);
                if (s < 0.95) {
                    scoreMap.put("科目", subjectName);
                    scoreMap.put("用户名", userName);
                    scoreMap.put("密码", password);
                    scoreMap.put("形考链接", urlTask);


                    System.out.println("答题不及格");
                    System.out.println(scoreMap.toString());
                } else {
                    completeInfo.setScore(score);
                    completeInfo.setComplete(true);
                    completeInfo.setHomeworkUrl(urlTask);
                    completeInfoList.add(completeInfo);
                }
            } catch (Exception e) {

            }

            //=============================12-19add======================
        }
        FileUtils.write(completeInfoFile, JSONObject.toJSONString(completeInfoList, SerializerFeature.PrettyFormat), "utf-8");
        Thread.sleep(10000);
        driver.close();
        driver.quit();
    }




    private static void closeDriver(WebDriver driver) {
        try {
            driver.close();
            driver.quit();
        } catch (Exception e) {

        }
    }

}
